import axios from "axios";
import config from "../../config/wx";

// axios.defaults.baseURL = "/weixin";
// const baseURL= '/weixin'
const baseURL = "https://api.weixin.qq.com";


// 微信正确请求
interface wxInfo {
  openid: string;
  nickname: string;
  sex: number;
  language: string;
  city: string;
  province: string;
  country: string;
  headimgurl: string;
  privilege: any[];
}
// 微信错误请求
interface wxErrorInfo {
  errcode: number;
  errmsg: string;
}


const getAccessTokenFn = async () => {
  // console.log(code);
  const ACCESS_TOKEN_RES = await axios({
    url: baseURL + "/cgi-bin/token",
    params: {
      // code: code,
      // appid: "wxb30e6b0efd171f58",
      appid: config.config.aid,
      secret: config.config.sec,
      // sec: "0cecc634a8178354cf9afa94656fbee3",
      grant_type: "client_credential",
    },
  });
  console.log(ACCESS_TOKEN_RES.data, "ACCESS_TOKEN_RES.data");
  const data = ACCESS_TOKEN_RES.data;
  // 获取失败
  return data;
};

// 获取手机号
// ?access_token=ACCESS_TOKEN
const getPhoneNumber = async (code:string, access_token: string) => {
  // console.log(code);
  const ACCESS_TOKEN_RES = await axios({
    // url: baseURL + "/wxa/business/getuserphonenumber",
    url:
      baseURL + "/wxa/business/getuserphonenumber?access_token=" + access_token,
    method: "post",
    params: {
      code,
      // access_token,
    },
  });
  console.log(ACCESS_TOKEN_RES.data, "ACCESS_TOKEN_RES.data");
  const data = ACCESS_TOKEN_RES.data;
  // 获取失败
  return data;
};

  // 获取userInfo
const getUserInfoFn = async (
    access_token: string,
    openid: string,
    num?:any
  ): Promise<wxInfo | wxErrorInfo> => {
    // console.log(access_token);
    // console.log(num);
    const USERINFO_RES = await axios({
      url: baseURL + "/sns/userinfo",
      params: {
        access_token,
        openid,
        lang: "zh_CN",
      },
    });
    // console.log(USERINFO_RES.data, "userInfo");
    const data = USERINFO_RES.data;
    if(data.errcode){
      // Taro.removeStorageSync("encryptedUserToken");
    }
    return data;
  };

//  /sns/oauth2/access_token?appid=APPID&sec=sec&code=CODE&grant_type=authorization_code
// 检查是否关注了公众号
const checkSubscribe = async (
  access_token: string,
  openid: string,
  num?: any
): Promise<wxInfo | wxErrorInfo> => {
  // console.log(access_token);
  console.log(num);
  const USERINFO_RES = await axios({
    url: baseURL + "/cgi-bin/user/info",
    params: {
      access_token,
      openid,
      lang: "zh_CN",
    },
  });
  console.log(USERINFO_RES.data, "USERINFO_RES.data");
  const data = USERINFO_RES.data;
  if (data.errcode) {
    // Taro.removeStorageSync("encryptedUserToken");
  }
  return data;
};

export default {
  axios,
  getAccessTokenFn,
  getUserInfoFn,
  checkSubscribe,
  getPhoneNumber,
};
// 处理 ACCESS_TOKEN_RES 响应
